<template>
  <el-scrollbar class="rcdg-side-navs">
    <ul v-if="navs.length" class="rcdg-side-navs-box" :style="{ width: width }">
      <li
        :class="['rcdg-side-navs-item', activeNav === nav.value ? 'is-active' : '']"
        v-for="nav in navs"
        :key="nav.value"
        :style="gap ? { marginBottom: gap } : {}"
        @click.stop="onNavClick(nav)">
        <i v-if="nav.icon" :class="['rcdg-side-navs-icon', nav.icon]"></i>
        <img class="rcdg-side-navs-icon" v-else-if="nav.img" src="" alt="图标" />
        <span class="rcdg-side-navs-txt">{{ nav.label }}</span>
      </li>
    </ul>
  </el-scrollbar>
</template>
<script>
export default {
  name: 'SideNavs',
  model: {
    prop: 'value',
    event: 'navChange',
  },
  props: {
    sources: {
      type: Array,
      default: () => [],
    },
    value: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({ label: 'label', value: 'value' }),
    },
    width: {
      type: String,
      default: '60px',
    },
    gap: {
      type: String,
      default: '',
    },
  },
  watch: {
    value: {
      handler(str) {
        if (str) {
          this.activeNav = str
        }
      },
    },
    sources: {
      handler(list) {
        if (list && list.length) {
          const navs = []
          list.forEach(item => {
            navs.push({
              label: item[this.options.label],
              value: item[this.options.value],
              ...item,
            })
          })
          this.navs = navs.concat()
          this.activeNav = this.value || navs[0].value
          this.$emit('navChange', this.activeNav)
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      activeNav: '',
      navs: [],
    }
  },
  methods: {
    onNavClick(nav) {
      if (this.activeNav === nav.value) {
        return false
      }
      this.activeNav = nav.value
      this.$emit('navChange', nav.value)
      this.$emit('change', nav, nav.value)
    },
  },
}
</script>
<style lang="scss" scoped>
.rcdg-side-navs {
  background-color: #ffffff;
  position: relative;
  &-box {
    padding: 20px 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  &-item {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    color: #333;
    &.is-active {
      color: #2b78f1;
    }
  }
  &-icon {
    width: 30px;
    height: 30px;
    font-size: 30px;
    margin-bottom: 6px;
  }
  &-txt {
    text-align: center;
    font-size: 13px;
  }
}
</style>
